package timing.ukulele.third.controller.weixin;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.bean.material.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.third.data.weixin.WxMaterialDTO;
import timing.ukulele.third.config.mp.WxMpConfiguration;
import timing.ukulele.third.util.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 微信素材管理
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/weixin/wxMaterial")
public class WxMaterialController {

    /**
     * /wxMaterial/materialFileUpload
     * @param appId
     * @param mediaType
     * @param mulFile
     * @return
     */
	@Operation(summary = "上传非图文微信素材")
	@PostMapping("/materialFileUpload")
	public ResponseData materialFileUpload(@RequestParam("appId") String appId,
                                           @RequestParam("mediaType") String mediaType,
                                           @RequestParam("file") MultipartFile mulFile,
                                           @RequestParam(value = "title", required = false) String title,
                                           @RequestParam(value = "introduction",required = false) String introduction) {
		try {
			WxMpMaterial material = new WxMpMaterial();
			material.setName(mulFile.getOriginalFilename());
			if(WxConsts.MediaFileType.VIDEO.equals(mediaType)){
				material.setVideoTitle(title);
				material.setVideoIntroduction(introduction);
			}
			File file = FileUtils.multipartFileToFile(mulFile);
			material.setFile(file);
			WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
			WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpMaterialService.materialFileUpload(mediaType,material);
			WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem();
			wxMpMaterialFileBatchGetResult.setName(file.getName());
			wxMpMaterialFileBatchGetResult.setMediaId(wxMpMaterialUploadResult.getMediaId());
			wxMpMaterialFileBatchGetResult.setUrl(wxMpMaterialUploadResult.getUrl());
			return ResponseData.success(wxMpMaterialFileBatchGetResult);
		} catch (WxErrorException e) {
            return ResponseData.error("上传非图文微信素材失败" + e);
		} catch (Exception e) {
            return ResponseData.error("上传失败" + e);
		}
	}

    /**
     * /wxMaterial/newsImgUpload
     * @param appId
     * @param mulFile
     * @return
     * @throws Exception
     */
	@Operation(summary = "上传图文消息内的图片")
	@PostMapping("/newsImgUpload")
	public ResponseData<String> newsImgUpload(@RequestParam("appId") String appId,
                                @RequestParam("file") MultipartFile mulFile) throws Exception {
		File file = FileUtils.multipartFileToFile(mulFile);
		WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
		WxMediaImgUploadResult wxMediaImgUploadResult = wxMpMaterialService.mediaImgUpload(file);
		return ResponseData.success(wxMediaImgUploadResult.getUrl());
	}

    /**
     * /wxMaterial/newsImgUpload
     * @param id
     * @param appId
     * @return
     */
    @Operation(summary = "通过ID删除微信素材")
    @DeleteMapping("/materialDel")
    public ResponseData<Boolean> materialDel(String id, String appId) {
        WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
        try {
            return ResponseData.success(wxMpMaterialService.materialDelete(id));
        } catch (WxErrorException e) {
            return ResponseData.error("删除微信素材失败" + e);
        }
    }

    /**
     * /wxMaterial/page
     * @param wxMaterialDTO
     * @return
     */
	@Operation(summary = "分页查询")
	@PostMapping("/page")
	public ResponseData getWxMaterialPage(@RequestBody WxMaterialDTO wxMaterialDTO) {
		try {
            WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(wxMaterialDTO.getAppId()).getMaterialService();
            int count = wxMaterialDTO.getPageSize();
            int offset = wxMaterialDTO.getCurrent() * count - count;
            Page page = new Page();
            if(WxConsts.MaterialType.NEWS.equals(wxMaterialDTO.getType())){
                WxMpMaterialNewsBatchGetResult result = wxMpMaterialService.materialNewsBatchGet(offset, count);
                page.setTotal(result.getTotalCount());
                page.setSize(wxMaterialDTO.getPageSize());
                page.setRecords(result.getItems());
            }else{
                WxMpMaterialFileBatchGetResult result = wxMpMaterialService.materialFileBatchGet(wxMaterialDTO.getType(), offset, count);
                page.setTotal(result.getTotalCount());
                page.setSize(wxMaterialDTO.getPageSize());
                if("video".equals(wxMaterialDTO.getType())) {
                    List<WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem> items = result.getItems();
                    for (WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem item : items) {
                        item.setUrl(wxMpMaterialService.materialVideoInfo(item.getMediaId()).getDownUrl());
                    }
                }
                page.setRecords(result.getItems());
            }
            return ResponseData.success(page);
		} catch (WxErrorException e) {
            return ResponseData.error("查询素材失败" + e);
		}
	}

	/**
	* /wxMaterial/getMaterialVideo
	* @param
	* @return R
	*/
	@Operation(summary = "获取微信视频素材")
	@GetMapping("/getMaterialVideo")
	public ResponseData<WxMpMaterialVideoInfoResult> getMaterialVideo(String appId, String mediaId) {
        WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
        try {
          return ResponseData.success(wxMpMaterialService.materialVideoInfo(mediaId));
        } catch (WxErrorException e) {
          return ResponseData.error("获取微信视频素材失败" + e);
        }
	}

	/**
	 * /wxMaterial/getMaterialOther
	 * @param
	 * @return R
	 */
	@Operation(summary = "获取微信素材直接文件")
	@GetMapping("/getMaterialOther")
	public ResponseEntity<byte[]> getMaterialOther(String appId, String mediaId, String fileName) throws Exception {
		try {
			WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
			//获取文件
			InputStream is = wxMpMaterialService.materialImageOrVoiceDownload(mediaId);
			byte[] body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			//设置文件类型
			headers.add("Content-Disposition", "attchement;filename=" +  URLEncoder.encode(fileName, "UTF-8"));
			headers.add("Content-Type", "application/octet-stream");
			HttpStatus statusCode = HttpStatus.OK;
			//返回数据
			ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
			return entity;
		} catch (WxErrorException e) {
			log.error("获取微信素材直接文件失败", e);
			return null;
		}
	}

	/**
	 * /wxMaterial/getTempMaterialOther
	 * @param
	 * @return R
	 */
	@Operation(summary = "获取微信临时素材直接文件")
	@GetMapping("/getTempMaterialOther")
	public ResponseEntity<byte[]> getTempMaterialOther(String appId, String mediaId,String fileName) throws Exception {
		try {
			WxMpMaterialService wxMpMaterialService = WxMpConfiguration.getMpServiceByAppId(appId).getMaterialService();
			//获取文件
			InputStream is = new FileInputStream(wxMpMaterialService.mediaDownload(mediaId));
			byte[] body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			//设置文件类型
			headers.add("Content-Disposition", "attchement;filename=" +  URLEncoder.encode(fileName, "UTF-8"));
			headers.add("Content-Type", "application/octet-stream");
			HttpStatus statusCode = HttpStatus.OK;
			//返回数据
			ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
			return entity;
		} catch (WxErrorException e) {
			e.printStackTrace();
			log.error("获取微信素材直接文件失败", e);
			return null;
		}
	}

}
